﻿using System;
using System.Web.Mvc;
using System.Web;
using System.IO;
using Citi.ExpenseReport.WebUI.Models;
using System.Collections.Generic;

namespace Citi.ExpenseReport.WebUI.Controllers
{
    public class ImportController : Controller
    {
        public ActionResult Upload(Util.ServiceIds fileType)
        {
            return View(fileType);
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file, Util.ServiceIds fileType)
        {
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Files"), fileName);
                file.SaveAs(path);

                var importModel = ExecuteRead(path, fileType);

                System.IO.File.Delete(path);

                return View("Results", importModel);
            }

            return RedirectToAction("Index");
        }

        private ImportModel ExecuteRead(string path, Util.ServiceIds fileType)
        {
            var errors = new List<ErrorModel>();
            var feeds = new List<FeedModel>();

            var startTime = DateTime.Now;
            var importHelper = new Util.ImportHelper();

            switch (fileType)
            {
                case Util.ServiceIds.Application:
                    feeds = importHelper.ImportApplication(path, ref errors);
                    break;
                case Util.ServiceIds.Telecom:
                    feeds = importHelper.ImportTelecom(path, ref errors);
                    break;
                case Util.ServiceIds.Desgold:
                    feeds = importHelper.ImportDesgold(path, ref errors);
                    break;
                case Util.ServiceIds.Email:
                    feeds = importHelper.ImportEmail(path, ref errors);
                    break;
                case Util.ServiceIds.Communicator:
                    feeds = importHelper.ImportCommunicator(path, ref errors);
                    break;
                case Util.ServiceIds.Workloud:
                    feeds = importHelper.ImportWorkloud(path, ref errors);
                    break;
                case Util.ServiceIds.BlackBerry:
                    feeds = importHelper.ImportBlackBerry(path, ref errors);
                    break;
            }

            return new ImportModel { Errors = errors, Feeds = feeds, ExecutionTime = DateTime.Now - startTime };
        }

        public ActionResult Results(ImportModel importModel)
        {
            return View(importModel);
        }
    }
}

